package com.lex.security.util;

import com.lex.common.exception.ApiException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 在添加日志等异步其他线程执行时，无法获取当前请求线程的ThreadLocal信息，无法获取用户信息
 * 通过SecurityUtils获取当前线程的用户信息
 */
public class SecurityUtils {
    /**
     * 获取用户账户
     **/
    public static String getUsername()
    {
        try
        {
            return getLoginUser().getUsername();
        }
        catch (Exception e)
        {
            throw new ApiException(e);
        }
    }

    /**
     * 获取用户
     **/
    public static UserDetails getLoginUser()
    {
        try
        {
            return (UserDetails) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            //抛出异常
            throw new ApiException(e);
        }
    }

    /**
     * 获取当前用户的Authentication
     */

    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
